package com.sxz.sbs.module.client;

import android.Manifest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.constant.TypeConstant;
import com.sxz.sbs.event.RecoverDetailPhoneEvent;
import com.sxz.sbs.event.RecoverPhoneEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.adapter.ClientDetailsAdapter;
import com.sxz.sbs.module.client.auth.RealNameActivity;
import com.sxz.sbs.module.client.auth.RealNameInfoActivity;
import com.sxz.sbs.module.client.bean.CallBean;
import com.sxz.sbs.module.client.bean.ClientDetailsBean;
import com.sxz.sbs.module.client.bean.ClientDetailsPlanBean;
import com.sxz.sbs.module.client.presenter.ClientDetailsPresenter;
import com.sxz.sbs.module.client.view.ClientDetailsView;
import com.sxz.sbs.util.AppointTimeUtils;
import com.sxz.sbs.widget.CommonTitle;
import com.sxz.sbs.widget.MultiplePhoneDialog;
import com.sxz.sbs.widget.StallAlertDialog;
import com.sxz.sbs.widget.UpdateRecordDialog;
import com.willy.ratingbar.ScaleRatingBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.telephony.TelephonyManager.CALL_STATE_IDLE;

/**
 * Created by hp on 2018/1/9.
 * @author hp
 * 客户详情界面
 */

public class ClientDetailsActivity extends BaseActivity<ClientDetailsPresenter> implements ClientDetailsView {
    @BindView(R.id.detail_scroll)
    NestedScrollView nestedScrollView;
    @BindView(R.id.recy_clientdetails)
    RecyclerView recyClientDetails;
    @BindView(R.id.simpleRatingBar)
    ScaleRatingBar scaleRatingBar;
    @BindView(R.id.tv_client_details_name)
    TextView tvClientDetailsName;
    @BindView(R.id.tv_detail_state)
    TextView tvState;
    @BindView(R.id.tv_callnum)
    TextView tvCallNum;
    @BindView(R.id.tv_calltime)
    TextView tvCallTime;
    @BindView(R.id.tv_detail_custom_address)
    TextView tvAddress;
    @BindView(R.id.tv_lookstall_time)
    TextView tvLookstallTime;
    @BindView(R.id.tv_addintentionclient)
    TextView tvAddIntentionClient;
    @BindView(R.id.tv_adddingjin)
    TextView tvAdddingjin;
    @BindView(R.id.tv_addchengjiao)
    TextView tvAddchengjiao;

    private OptionsPickerView pvOptions;
    private ClientDetailsBean mdata;
    private ClientDetailsAdapter clientADetailsdapter;
    public boolean mIsLive = true;
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private String[] str1 = {"05时", "06时", "07时", "08时", "09时", "10时", "11时", "12时", "13时", "14时", "15时", "16时", "17时", "18时", "19时", "20时"};
    private String textTime = "";
    private Intent intent;

    private int customId;
    private int currentPage = 1;

    private String callPhone = "";
    private Intent phoneIntent;
    private BroadcastReceiver callReceiver;
    private TelephonyManager tm;
    private boolean isCall;
    private String endTime = "";
    private IntentFilter intentFilter;
    private boolean isRegistered = true;
    private String textPara = "";

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        customId = getIntent().getIntExtra(IntentConstant.CUSTOM_ID, 0);
        textPara = getIntent().getStringExtra("txt_para");
        if (textPara == null) {
            textPara = "";
        }
        callReceiver = new CallReceiver();
        intentFilter = new IntentFilter("call_action");
        registerReceiver(callReceiver, intentFilter);
        getOptionData();
        initOptionPicker();
        recyClientDetails.setNestedScrollingEnabled(false);
    }

    @Override

    protected void onResume() {
        super.onResume();
        getClientData();
        getClientPlanData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_clientdetails;
    }

    @Override
    protected ClientDetailsPresenter createPresenter() {
        return new ClientDetailsPresenter();
    }


    @OnClick({R.id.hcv_base_info, R.id.img_record, R.id.rela_callrecords,
            R.id.tv_lookstall_time, R.id.tv_addintentionclient, R.id.tv_adddingjin,
            R.id.tv_addchengjiao, R.id.hcv_deal_record, R.id.hcv_compact_file, R.id.hcv_deposit_file
            , R.id.iv_detail_call, R.id.hcv_id_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.hcv_base_info:
                intent = new Intent(ClientDetailsActivity.this, ClientBasicsMsgActivity.class);
                intent.putExtra(IntentConstant.CUSTOM_ID, customId);
                startActivity(intent);
                break;
            case R.id.img_record:
                intent = new Intent(ClientDetailsActivity.this, ClientEvaluateActivity.class);
                intent.putExtra("clientid", mdata.getId());
                intent.putExtra("starnum", mdata.getVal_StarLevel() + "");
                startActivity(intent);
                break;
            case R.id.rela_callrecords://   通话记录
                if (mdata == null) {
                    return;
                }
                intent = new Intent(ClientDetailsActivity.this, CallRecordsActivity.class);
                intent.putExtra("client_detail_bean", mdata);
                startActivity(intent);
                closeRes();
                break;
            case R.id.tv_lookstall_time:
                if (pvOptions != null) {
                    pvOptions.show();
                }
                break;
            case R.id.tv_addintentionclient:
                //  添加意向客户
                setAddIntentionClient();
                break;
            case R.id.tv_adddingjin:
                //  定金
                if (mdata != null) {
                    startActivity(new Intent(this, EvidenceActivity.class)
                            .putExtra("deal_evidence", mdata));
                }
                break;
            case R.id.tv_addchengjiao:
                //  成交
                if (mdata != null) {
                    startActivity(new Intent(this, DealEvidenceActivity.class)
                            .putExtra("deal_evidence", mdata));
                }
                break;
            case R.id.hcv_deal_record:
                //  交易记录
                if (mdata == null) {
                    return;
                }
                intent = new Intent(ClientDetailsActivity.this, DealRecordActivity.class);
                intent.putExtra(IntentConstant.CUSTOM_ID, mdata.getId());
                startActivity(intent);
                break;
            case R.id.hcv_compact_file:
                //  合同文件
                if (mdata == null) {
                    return;
                }
                startActivity(new Intent(this, CompactListActivity.class)
                        .putExtra("compact_type", 2)
                        .putExtra(IntentConstant.CUSTOM_ID, mdata.getId()));
                break;
            case R.id.hcv_deposit_file:
                //  定金凭证
                if (mdata == null) {
                    return;
                }
                startActivity(new Intent(this, CompactListActivity.class)
                        .putExtra("compact_type", 1)
                        .putExtra(IntentConstant.CUSTOM_ID, mdata.getId()));
                break;
            case R.id.iv_detail_call:
                //  打电话
                if (mdata == null) {
                    return;
                }
                PermissionUtils.permission("android.permission.CALL_PHONE", "android.permission.READ_CALL_LOG").callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        if (!TextUtils.isEmpty(mdata.getTxt_Phone())) {
                            String[] phoneArr = mdata.getTxt_Phone().split("\\,");
                            if (phoneArr.length <= 0) {
                                ToastUtils.showShort("无手机号");
                                return;
                            }
                            if (phoneArr.length > 0 && phoneArr.length <= 1) {
                                if (!TextUtils.isEmpty(phoneArr[0])) {
                                    callPhone = phoneArr[0];
                                    new StallAlertDialog.Builder(ClientDetailsActivity.this)
                                            .showTitle(false)
                                            .setMessage(callPhone)
                                            .setPositiveButton("呼叫", new StallAlertDialog.OnPositiveListener() {
                                                @Override
                                                public void onPositiveClick(View view) {
                                                    phoneIntent = new Intent("call_action");
                                                    sendBroadcast(phoneIntent);
                                                    Intent intent = new Intent();
                                                    intent.setAction(Intent.ACTION_CALL);
                                                    intent.setData(Uri.parse("tel:" + callPhone));
                                                    startActivity(intent);

                                                }
                                            }).create().show();
                                } else {
                                    ToastUtils.showShort("无手机号");
                                }
                            } else if (phoneArr.length > 1) {
                                List<String> phones = new ArrayList<String>();
                                for (int i = 0; i < phoneArr.length; i++) {
                                    if (!TextUtils.isEmpty(phoneArr[i])) {
                                        phones.add(phoneArr[i]);
                                    }
                                }
                                MultiplePhoneDialog dialog = new MultiplePhoneDialog(ClientDetailsActivity.this, phones);
                                dialog.setOnChosePhoneListener(new MultiplePhoneDialog.OnChosePhoneListener() {
                                    @Override
                                    public void onSelectPhone(String phone) {
                                        callPhone = phone;
                                        phoneIntent = new Intent("call_action");
                                        sendBroadcast(phoneIntent);
                                        Intent intent = new Intent();
                                        intent.setAction(Intent.ACTION_CALL);
                                        intent.setData(Uri.parse("tel:" + callPhone));
                                        startActivity(intent);
                                    }
                                });
                                dialog.show();
                            }
                        } else {
                            ToastUtils.showShort("无手机号");
                        }
                    }

                    @Override
                    public void onDenied() {
                        ToastUtils.showShort("请授予打电话和读取通话记录权限");
                    }
                }).request();

                break;
            case R.id.hcv_id_info:
                if (mdata != null) {
                    if (mdata.getIsRealName() == 1) {
                        //已上传
                        startActivity(new Intent(this, RealNameInfoActivity.class)
                                .putExtra(IntentConstant.CUSTOM_ID, mdata.getId()));
                    } else if (mdata.getIsRealName() == 2) {
                        //未上传
                        startActivity(new Intent(this, RealNameActivity.class)
                                .putExtra(IntentConstant.CUSTOM_ID, mdata.getId()));
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取客户简洁版信息成功结果
     *
     * @param data
     */
    @Override
    public void onClientDetailsSuccess(ClientDetailsBean data) {
        if (mIsLive && data != null) {
            mdata = data;
            if (data.getVal_StarLevel() <= 0) {
                scaleRatingBar.setVisibility(View.GONE);
            } else {
                scaleRatingBar.setVisibility(View.VISIBLE);
                scaleRatingBar.setNumStars(data.getVal_StarLevel());
                scaleRatingBar.setRating(data.getVal_StarLevel());
            }
            new CommonTitle.Builder(this).setTitle(data.getTxt_UserName()).build().show();

            tvClientDetailsName.setText(data.getTxt_UserName());
            tvState.setText(data.getDisplayStatus());
            if (data.getVal_Type() == TypeConstant.VAL_TYPE_HAVE) {
                tvAddIntentionClient.setVisibility(View.GONE);
            }
            if (data.getCallCount() == 0) {
                tvCallNum.setText("已通话0次");
            } else {
                tvCallNum.setText("已通话" + data.getCallCount() + "次" + "   最近："
                        + data.getCallTime());
            }
            tvLookstallTime.setText(data.getAptTime());
            tvAddress.setText(data.getAddr_Address());

        }
    }

    /**
     * 获取客户进度成功结果
     *
     * @param data
     */
    @Override
    public void onClientDetailsPlanSuccess(ClientDetailsPlanBean data) {
        if (mIsLive && data != null) {
            clientADetailsdapter = new ClientDetailsAdapter(data.getList());
            recyClientDetails.setLayoutManager(new LinearLayoutManager(this));
            recyClientDetails.setAdapter(clientADetailsdapter);
        }
    }

    /**
     * 预约看车位
     *
     * @param data
     */
    @Override
    public void onLookStallSuccess(String data) {
        ToastUtils.showShort("预约提交成功");
    }

    /**
     * 添加意向客户
     *
     * @param data
     */
    @Override
    public void onAddIntentionClientSuccess(String data) {
        ToastUtils.showShort("添加成功,请到意向客户列表里查看");
        tvAddIntentionClient.setVisibility(View.GONE);
    }

    @Override
    public void onAddCallRecordSuccess() {
        getClientData();
    }

    /**
     * 获取客户简洁版信息请求
     */
    private void getClientData() {
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", customId);
        mPresenter.getClientDetails(map);
    }

    /**
     * 获取客户进度请求
     */
    private void getClientPlanData() {
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", customId);
        map.put("pageNumber", currentPage);
        map.put("pageSize", AppConstant.PAGE_SIZE);
        mPresenter.getClientDetailsPlan(map);
    }

    /**
     * 约看车位请求
     */
    private void setLookStall(String time) {
        // aptTime	string	是	预约时间 2018-01-16 星期二 18时
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", customId);
        map.put("aptTime", time);
        mPresenter.getLookStall(map);
    }

    /**
     * 新增意向客户请求
     */
    private void setAddIntentionClient() {
        /**
         customId	int	是	客户ID
         valType	int	是	1：移除、2：新增
         */
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", customId);
        map.put("valType", TypeConstant.VAL_TYPE_HAVE);
        mPresenter.getAddIntentionClient(map);
    }

    /**
     * 约看车位时间
     */
    private void initOptionPicker() {//条件选择器初始化
        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                textTime = options1Items.get(options1)
                        + " " + options2Items.get(options1).get(options2);
                tvLookstallTime.setText(textTime);
                nestedScrollView.scrollTo(0, 0);
                setLookStall(textTime);

            }
        }).isCenterLabel(false)
                .setBackgroundId(0x66000000)
                .build();
        pvOptions.setPicker(options1Items, options2Items);
    }

    private void getOptionData() {
        List<String> data = new AppointTimeUtils().setTime();
        //选项1
        for (int i = 0; i < data.size(); i++) {
            options1Items.add(data.get(i));
        }
        //选项2
        ArrayList<String> options2Items_01 = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        int currentHour = c.get(Calendar.HOUR_OF_DAY);
        for (int i = currentHour + 1; i < 24; i++) {
            if (i < 10) {
                options2Items_01.add("0" + i + "时");
            } else {
                options2Items_01.add(i + "时");
            }

        }

        ArrayList<String> options2Items_02 = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            if (i < 10) {
                options2Items_02.add("0" + i + "时");
            } else {
                options2Items_02.add(i + "时");
            }
        }

        if (options2Items_01.size() <= 0) {
            options1Items.remove(0);
        } else {
            options2Items.add(options2Items_01);
        }
        for (int i = 0; i < 6; i++) {
            options2Items.add(options2Items_02);
        }
    }

    private class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("action" + intent.getAction());
            //如果是去电
            if (!intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
                tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
            }
        }
    }

    PhoneStateListener listener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //注意，方法必须写在super方法后面，否则incomingNumber无法获取到值。
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case CALL_STATE_IDLE:
                    if (isCall) {
                        isCall = false;
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        getCallRecord();
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    isCall = true;
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    break;
                default:
                    break;
            }
        }
    };

    private void getCallRecord() {
        ContentResolver resolver = getContentResolver();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI,
                new String[]{CallLog.Calls.CACHED_NAME
                        , CallLog.Calls.NUMBER
                        , CallLog.Calls.DATE
                        , CallLog.Calls.DURATION
                        , CallLog.Calls.TYPE}
                , CallLog.Calls.NUMBER + "=" + callPhone, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        // 3.通过Cursor获得数据
        List<CallBean> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
            String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
            long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
            int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
            int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
            String typeString = "";
            switch (type) {
                case CallLog.Calls.INCOMING_TYPE:
                    typeString = "打入";
                    break;
                case CallLog.Calls.OUTGOING_TYPE:
                    typeString = "打出";
                    break;
                case CallLog.Calls.MISSED_TYPE:
                    typeString = "未接";
                    break;
                default:
                    break;
            }
            CallBean callBean = new CallBean();
            callBean.setName((name == null) ? "未备注联系人" : name);
            callBean.setNumber(number);
            callBean.setDate(date);
            callBean.setDuration(duration);
            callBean.setType(typeString);
            list.add(callBean);
        }
        cursor.close();

        if (list != null && list.size() > 0) {
            //  查询出了数据
            final CallBean callBean = list.get(0);
            if (callBean.getDuration() > 0) {
                if (textPara.equals("valType=1&valStatus=0") || textPara.equals("valType=3&valStatus=0")) {
                    UpdateRecordDialog dialog = new UpdateRecordDialog(this);
                    dialog.setOnUpdateDialogListener(new UpdateRecordDialog.OnUpdateDialogListener() {
                        @Override
                        public void onClose(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                        }

                        @Override
                        public void onToIntent(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                            setAddIntentionClient();
                        }

                        @Override
                        public void onToUpdate(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                            Intent intent = new Intent(ClientDetailsActivity.this, ClientEvaluateActivity.class);
                            intent.putExtra("clientid", mdata.getId());
                            intent.putExtra("starnum", mdata.getVal_StarLevel() + "");

                            startActivity(intent);
                        }
                    });
                    dialog.show();
                } else {
                    new StallAlertDialog.Builder(this).showTitle(false)
                            .setMessage("是否需要更新跟进记录？")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(false)
                            .setNegativeButton(new StallAlertDialog.OnNegativeListener() {
                                @Override
                                public void onNegativeClick(View view) {
                                    addCallRecord(callBean);
                                }
                            })
                            .setPositiveButton(new StallAlertDialog.OnPositiveListener() {
                                @Override
                                public void onPositiveClick(View view) {
                                    addCallRecord(callBean);
                                    Intent intent = new Intent(ClientDetailsActivity.this, ClientEvaluateActivity.class);
                                    intent.putExtra("clientid", mdata.getId());
                                    intent.putExtra("starnum", mdata.getVal_StarLevel() + "");
                                    startActivity(intent);
                                }
                            })
                            .create().show();
                }


            }

        }
        Log.e("查询记录", list.toString());

    }

    /**
     * 新增通话记录
     */
    private void addCallRecord(CallBean callBean) {
        endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", mdata.getId());
        map.put("callBeginTime", callBean.getDate());
        map.put("callEndTime", endTime);
        mPresenter.addCallRecord(map);

    }

    private void closeRes() {
        if (tm != null) {
            tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        }
        unregisterReceiver(callReceiver);
        isRegistered = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecoverDetailEvent(RecoverDetailPhoneEvent event) {
        callReceiver = new CallReceiver();
        registerReceiver(callReceiver, intentFilter);
        isRegistered = true;
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().post(new RecoverPhoneEvent());
        if (tm != null) {
            tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        }
        if (isRegistered) {
            unregisterReceiver(callReceiver);
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
